<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of WhitelabelController
 *
 * @author pohnean
 */
class WhitelabelController extends PsController
{

	public $layout = 'manage';

	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'roles' => array('ManageAgency.SystemSettings.Manage'),
					),
						), parent::accessRules());
	}

	public function moduleAccessRules()
	{
		return array(
			array('Propsage.WhiteLabel')
		);
	}

	public function actionIndex()
	{
		$agency = $this->loadAgency();
		$agencySettings = array();

		if ($agency->settings != null) {
			$agencySettings = $agency->settings;
		}
		$defaultSettings = $agency->defaultSettings;

		if (!empty($_POST['AgencySetting'])) {
			$newAgencySettings = $_POST['AgencySetting'];
			
			try {
				$tx = Yii::app()->db->beginTransaction();

				// set empty values to default values
				unset($agencySettings['WhiteLabel']);
				foreach ($newAgencySettings['WhiteLabel'] as $key => $value) {
					if (empty($value)) {
						$value = $defaultSettings['WhiteLabel'][$key];
					}
					$newAgencySettings['WhiteLabel'][$key] = trim($value);
				}
				$agency->settings = CMap::mergeArray($agencySettings, $newAgencySettings);

				// Update calendar names
				$sql = "UPDATE `cal_calendar` t INNER JOIN `user` u ON (t.user_id = u.id) SET t.displayname = :new_displayname WHERE u.agency_id = :agency_id";
				Yii::app()->db->createCommand($sql)->execute(array(
					':new_displayname' => $agency->settings['WhiteLabel']['CalendarName'],
					':agency_id' => $agency->id
				));

				$agency->save(true, array('settings'));

				$tx->commit();

				PsSystemMessage::add('Your changes have been saved.', 'success');
				$this->refresh();
			} catch (CDbException $e) {
				$tx->rollback();
			}
		}

		$data = array();
		$data['agency'] = $agency;
		$this->render('index', $data);
	}

	/**
	 * @return Agency the agency of the currently logged on user.
	 */
	public function loadAgency()
	{
		return Yii::app()->user->model->agency;
	}

}

?>
